import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { tableConfig, header } from '../data/config'
import { getUrlParam } from '../data/util'
import store from 'store'

const base             = url.base,
      bank             = url.bank,
      minshengBank     = url.minshengBank,
      getPledgedList   = request.getPledgedList,
      getChannelList   = request.getChannelList,
      getPledgedExcel  = request.getPledgedExcel,
      capital          = request.capital,
      balance          = request.balance,
      thaw             = request.thaw,
      refund           = request.refund,
      refunded         = request.refunded,
      notice           = request.notice,
      contract         = request.contract,
      patchThaw        = request.patchThaw,
      pathRefund       = request.pathRefund,
      getPledgedArea   = request.getPledgedArea,
      getBuildTypeList = request.getBuildTypeList,
      getBuildArea     = request.getBuildArea;

let table,
    storeData,
    // 银行查询接口,银行不同接口有可能不同
    bankUrl,
    auth               = store.get('auth'),
    // 用户类型
    loginType          = store.get('loginType'),
    // 解冻
    isThaw             = auth.indexOf('identityCard-confess-thaw') !== -1,
    // 退款
    isRcjRefund        = auth.indexOf('identityCard-confess-rcjRefund') !== -1,
    // 已退
    isUpdateStatus     = auth.indexOf('identityCard-confess-updateStatus') !== -1,
    // 余额查询 所有人都有权限
    // isCheckMoney       = auth.indexOf('identityCard-confess-checkMoney') !== -1,
    isCheckMoney       = true,
    // 验资、验资通过
    isSynchroBlance    = auth.indexOf('identityCard-confess-synchroBlance') !== -1,
    // 交易退款
    isRcjRefund2       = auth.indexOf('identityCard-confess-rcjRefund2') !== -1,
    // 废弃
    isScrap            = isUpdateStatus,
    // 合同下载
    isDownLoadContract = auth.indexOf('identityCard-confess-downLoadContract') !== -1,
    // 批量解冻
    isBathThaw         = auth.indexOf('identityCard-confess-batchThaw') !== -1,
    // 批量退款
    isBathRefund       = auth.indexOf('identityCard-confess-batchRawRet') !== -1,
    // 导出
    isExport           = auth.indexOf('identity-download-excel') !== -1

console.log('==========================')
console.log('解冻:' + isThaw)
console.log('退款:' + isRcjRefund)
console.log('已退:' + isUpdateStatus)
console.log('余额查询:' + isCheckMoney)
console.log('验资、验资通过:' + isSynchroBlance)
console.log('交易退款:' + isRcjRefund2)
console.log('废弃:' + isScrap)
console.log('合同下载:' + isDownLoadContract)
console.log('批量解冻:' + isBathThaw)
console.log('批量退款:' + isBathRefund)
console.log('==========================')

// 判断是否有批量解冻和批量退款权限
if (isBathThaw) {
  $('#batch-thaw').show()
} else {
  $('#batch-thaw').hide().remove()
}

if (isBathRefund) {
  $('#batch-refund').show()
} else {
  $('#batch-refund').hide().remove()
}

// 判断登录用户类型是否显示省和市
if (loginType === 1 || loginType === 2) {
  $('#provinceSearchSelect').hide().remove()
  $('#citySearchSelect').hide().remove()
} else {
  $('#provinceSearchSelect').show()
  $('#citySearchSelect').show()
}

if (isExport) {
  $('#export').show()
} else {
  $('#export').hide().remove()
}

// 初始化表格
table = $('#table').bootstrapTable($.extend({}, tableConfig, {
  url: base + getPledgedList,
  queryParams: function (params) {
    return $.extend({
      currentPage: params.pageNumber,
      pageSize: params.pageSize,
      clickToSelect: true,
    }, $('#searchForm').serializeObject())
  },
  ajax: function (params) {  //  自定义ajax
    $.ajax({
      headers: header,
      url: params.url,
      type: params.type,
      contentType: params.contentType,
      data: params.data
    })
      .done(function (res) {

        let totalAmount = $('.totalAmount')

        if (!totalAmount.length) {    // 新增统计金额

          let amount = (res.object.totalAmount / 100).toFixed(2).toString().split('.'),
              html   = `<div class="pull-left totalAmount">
                        <span class="amountTitle"></span><span class="amount">${ String(amount[0]).replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') }.<small>${ amount[1] }</small></span>
                        <span class="unit"> 元</span>
                      </div>`

          $('.fixed-table-pagination').before(html)

        } else {
          $('.totalAmount .amount').text(( res.object.totalAmount / 100).toFixed(2))
        }

        params.success({
          total: res.object.data.totalRows,
          rows: res.object.data.elements
        })
      })
      .fail(function (res) {
        console.log("error")
        console.log(res)

      })
      .always(function (res) {

        console.log("complete")
      });

  },
  columns: [
    {
      field: 'checked',
      valign: 'middle',
      checkbox: true
    },
    {
      field: 'idStr',
      class: 'word-break',
      width: '130px',
      title: '业务流水号',
      valign: 'middle'
    }, {
      field: 'propertyName',
      title: '楼盘名称',
      valign: 'middle'
    }, {
      field: 'termId',
      class: 'word-break',
      title: '终端号',
      valign: 'middle'
    }, {
      field: 'tradeDate',
      title: '交易时间',
      valign: 'middle',
      width: '160px',
      formatter: (index, row) => {
        return moment(index).format('YYYY-MM-DD HH:mm:ss')
      }
    }, {
      field: 'tradeAmount',
      title: '担保金金额',
      valign: 'middle',
      width: '100px',
      formatter: (index, row) => {
        return (index / 100).toFixed(2)
      }
    }, {
      field: 'payAmount',
      title: '已收金额',
      width: '100px',
      valign: 'middle',
      formatter: (index, row) => {
        return (index / 100).toFixed(2)
      }
    }, {
      field: 'name',
      title: '姓名',
      width: '90px',
      valign: 'middle'
    }, {
      field: 'bankName',
      title: '所属银行',
      width: '90px',
      valign: 'middle'
    }, {
      field: 'phone',
      title: '手机号',
      valign: 'middle'
    }, {
      field: 'bankNum',
      title: '返还担保金借记卡卡号',
      valign: 'middle'
    }, {
      field: 'withdrawTime',
      title: '退款时间',
      valign: 'middle',
      width: '160px',
      formatter: (index, row) => {
        return index ? moment(index).format('YYYY-MM-DD HH:mm:ss') : ''
      }
    }, {
      field: 'payStatus',
      title: '状态',
      valign: 'middle',
      class: 'strong',
      width: '100px',
      formatter: (index, row) => {
        switch (index) {
          case "1":
            return '支付成功'
            break
          case "2":
            return row.freezeLog
            break
          case "3":
            return '退款中'
            break
          case "4":
            return row.freezeLog
            break
          case "5":
            return '退款审核未通过'
            break
          case "6":
            return row.freezeLog
            break
          case "7":
            return '已创建结算单'
            break
          case "8":
            return '结算审核中'
            break
          case "9":
            return '结算待确认'
            break
          case "10":
            return '结算成功'
            break
          case "11":
            return '结算失败'
            break
          case "12":
            return '待控制'
            break
        }
      }
    }, {
      field: 'payStatus',
      valign: 'middle',
      align: 'center',
      width: '300px',
      title: '操作',
      formatter: function (index, row) {
        index = String(index)

        if (index === '1') {
          // 根据按钮数量来展示
          let btnCount = 1

          isCheckMoney && btnCount++
          isThaw && row.freezeStatus === "success" && btnCount++
          isRcjRefund && row.freezeStatus === "unfreeze" && btnCount++
          isUpdateStatus && btnCount++
          isDownLoadContract && btnCount++

          if (btnCount > 2) {
            return `<div class="btn-group">
                    <button data-id="${ row.idStr }" data-icNo="${ row.icNo }" type="button" class="btn btn-default notice">告知书下载</button>
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" >
                       <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu pull-right">                   
                     ${ isCheckMoney ? `<li><a href="#" data-id="${ row.idStr }" class="balance">余额</a></li>` : ''}
                     
                     ${ isThaw && row.freezeStatus === "success" ? `<li><a href="#" data-id="${ row.idStr }" class="thaw">解冻</a></li>` : ''}
                 
                     ${ isRcjRefund && row.freezeStatus === "unfreeze" ? `<li><a href="#" data-id="${ row.idStr }" data-name="${ row.name }" class="refund">退款</a></li>` : ''}   
                                       
                     ${ isUpdateStatus ? `<li><a href="#" data-id="${ row.idStr }" data-name="${ row.name }" class="refunded">已退</a></li>` : ''}
                    
                     ${ isDownLoadContract ? `<li><a href="#" data-id="${ row.idStr }" data-icNo="${ row.icNo }" class="contract">合同下载</a></li>` : ''}
                     </ul>                                                                                            
                  </div>`
          }

          return `<div class="btn-group">
                    ${ isCheckMoney ? `<button data-id="${ row.idStr }" type="button" class="btn btn-default balance">余额</button>` : ''}
                    ${ isThaw && row.freezeStatus === "success" ? `<button data-id="${ row.idStr }" type="button" class="btn btn-default thaw">解冻</button>` : ''}
                    ${ isRcjRefund && row.freezeStatus === "unfreeze" ? `<button data-id="${ row.idStr }" data-name="${ row.name }" type="button" class="btn btn-default refund">退款</button>` : ''}
                    ${ isUpdateStatus ? `<button data-id="${ row.idStr }" data-name="${ row.name }" type="button" class="btn btn-default refunded">已退</button>` : ''}
                    ${ isDownLoadContract ? `<button data-id="${ row.idStr }" data-icNo="${ row.icNo }" type="button" class="btn btn-default contract">合同下载</button>` : ''}
                    <button data-id="${ row.idStr }" data-icNo="${ row.icNo }" type="button" class="btn btn-default notice">告知书下载</button>
                  </div>`
        }

        if (index === '6') {

          // 根据按钮数量来展示
          let btnCount = 1

          isCheckMoney && btnCount++
          isRcjRefund && row.freezeStatus == "unfreeze" && btnCount++
          isUpdateStatus && btnCount++

          if (btnCount > 2) {
            return `<div class="btn-group">
                    <button data-id="${ row.idStr }" data-icNo="${ row.icNo }" type="button" class="btn btn-default notice">告知书下载</button>
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" >
                       <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu pull-right">                   
                     ${ isCheckMoney ? `<li><a href="#" data-id="${ row.idStr }" class="balance">余额</a></li>` : ''}
                 
                     ${ isRcjRefund && row.freezeStatus == "unfreeze" ? `<li><a href="#" data-id="${ row.idStr }" data-name="${ row.name }" class="refund">退款</a></li>` : ''}   
                                       
                     ${ isUpdateStatus ? `<li><a href="#" data-id="${ row.idStr }" data-name="${ row.name }" class="refunded">已退</a></li>` : ''}
                               
                     </ul>                                                                                            
                  </div>`
          }

          return `<div class="btn-group">
                    ${ isCheckMoney ? `<button data-id="${ row.idStr }" type="button" class="btn btn-default balance">余额</button>` : ''}
                    ${ isRcjRefund && row.freezeStatus == "unfreeze" ? `<button data-id="${ row.idStr }" data-name="${ row.name }" type="button" class="btn btn-default refund">退款</button>` : ''}
                    ${ isUpdateStatus ? `<button data-id="${ row.idStr }" data-name="${ row.name }" type="button" class="btn btn-default refunded">已退</button>` : ''}
                    <button data-id="${ row.idStr }" data-icNo="${ row.icNo }" type="button" class="btn btn-default notice" data-toggle="dropdown" >告知书下载</button>
                  </div>`
        }

        if (index === '12') {

          // 根据按钮数量来展示
          let btnCount = 1

          isCheckMoney && btnCount++
          isRcjRefund && btnCount++
          isSynchroBlance && btnCount++
          isScrap && btnCount++

          if (btnCount > 2) {

            // ${ isSynchroBlance ? `<li><a href="#" data-id="${ row.idStr }" class="capitalPass">验资通过</a></li>` : ''}

            return `<div class="btn-group">
                    <button data-id="${ row.idStr }" data-icNo="${ row.icNo }" type="button" class="btn btn-default notice">告知书下载</button>
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" >
                       <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu pull-right">  
                     ${ isSynchroBlance ? `<li><a href="#" data-id="${ row.idStr }" class="capital">验资</a></li>` : ''}
                                     
                     ${ isCheckMoney ? `<li><a href="#" data-id="${ row.idStr }" class="balance">余额</a></li>` : ''}
                 
                     ${ isRcjRefund ? `<li><a href="#" data-id="${ row.idStr }" data-name="${ row.name }" class="refund">退款</a></li>` : ''}   
                                                                       
                     ${ isScrap ? `<li><a href="#" data-id="${ row.idStr }" data-name="${ row.name }" class="scrap">废弃</a></li>` : ''}
                     </ul>                                                                                            
                  </div>`
          }

          // ${ isSynchroBlance ? `<button data-id="${ row.idStr }" type="button" class="btn btn-default capitalPass">验资通过</button>` : ''}

          return `<div class="btn-group">
                    ${ isCheckMoney ? `<button data-id="${ row.idStr }" type="button" class="btn btn-default balance">余额</button>` : ''}
                    
                    ${ isSynchroBlance ? `<button data-id="${ row.idStr }" type="button" class="btn btn-default capital">验资</button>` : ''}
                    
                    
                    ${ isUpdateStatus ? `<button data-id="${ row.idStr }" data-name="${ row.name }" type="button" class="btn btn-default refund">退款</button>` : ''}
                    
                    ${ isScrap ? `<button data-id="${ row.idStr }" data-name="${ row.name }" type="button" class="btn btn-default scrap">废弃</button>` : ''}
                    
                    <button data-id="${ row.idStr }" data-icNo="${ row.icNo }" type="button" class="btn btn-default notice">告知书下载</button>
                  </div>`
        }

        return `<div class="btn-group">                                        
                  ${ isCheckMoney ? `<button data-id="${ row.idStr }" type="button" class="btn btn-default balance">余额</button>` : ''}                             
                  <button data-id="${ row.idStr }" data-icNo="${ row.icNo }" type="button" class="btn btn-default notice" >告知书下载</button>     
                </div>`

      }
    }]
}))

table.on('load-success.bs.table', () => {
  $('.amountTitle').html('担保金金额 : ')
})

// 初始化日期选择器
$('#operateStartDate').datetimepicker({
  format: "yyyy-mm-dd",
  startView: 3,
  minView: 2,
  autoclose: true
})

$('#operateEndDate').datetimepicker({
  format: "yyyy-mm-dd",
  startView: 3,
  minView: 2,
  autoclose: true
})

let buildSelectize

// 初始化银行
getBank();
// 初始化省
getProvince();
// 初始化楼盘
getBuild()

// 动态加载城市
$('#provinceSearch').on('change', function () {
  let provinceId = $('#provinceSearch').children('option:selected').val(),
      cityId     = $('#citySearch').children('option:selected').val();

  getCity(provinceId)
  getBuild(provinceId, '')
  buildSelectize.destroy()
})

// 动态加载楼盘
$('#citySearch').on('change', function () {
  let provinceId = $('#provinceSearch').children('option:selected').val(),
      cityId     = $('#citySearch').children('option:selected').val();

  getBuild(provinceId, cityId)
  buildSelectize.destroy()
})

// 动态加载楼盘户型
$('#propertyId').on('change', function () {
  let propertyId = $('#propertyId').children('option:selected').val();

  getBuildType(propertyId)
})

function getBank () {

  $.ajax({
    headers: header,
    url: base + getChannelList
  })
    .done(function (res) {
      console.log("初始化银行 success")
      console.log(res)

      let channel = $('#channel'),
          html    = '<option value="">请选择</option>',
          i       = 0,
          data    = res.object,
          len     = data.length;

      for (; i < len; i++) {
        html += `<option value="${ data[i].channelCode }">${ data[i].channelName }</option>`
      }

      channel.html(html)
    })
    .fail(function (res) {
      console.log(res)

      layer.msg('获取银行失败', {
        icon: 5
      })
    })
    .always(function (res) {

      console.log("complete")
    })

}

function getProvince () {

  $.ajax({
    headers: header,
    url: base + getPledgedArea,
    data: {
      searchTypeId: 0
    }
  })
    .done(function (res) {
      console.log("初始化省 success")
      console.log(res)

      let dom  = $('#provinceSearch'),
          html = '<option value="">请选择</option>',
          i    = 0,
          data = res,
          len  = data.length;

      for (; i < len; i++) {
        html += `<option value="${ data[i].id }">${ data[i].name }</option>`
      }

      dom.html(html)
      dom.selectize()

    })
    .fail(function (res) {
      console.log(res)

      layer.msg('获取省失败', {
        icon: 5
      })
    })
    .always(function (res) {

      console.log("complete")
    })
}

function getCity (id) {
  console.log(id)
  $.ajax({
    headers: header,
    url: base + getPledgedArea,
    data: {
      searchTypeId: 1,
      parentId: id
    }
  })
    .done(function (res) {
      console.log("初始化省 success")
      console.log(res)

      let dom  = $('#citySearch'),
          html = '<option value="">请选择</option>',
          i    = 0,
          data = res,
          len  = data.length;

      for (; i < len; i++) {
        html += `<option value="${ data[i].id }">${ data[i].name }</option>`
      }

      dom.html(html)

    })
    .fail(function (res) {
      console.log(res)

      layer.msg('获取城市失败', {
        icon: 5
      })
    })
    .always(function (res) {

      console.log("complete")
    })
}

function getBuild (provinceId, cityId) {
  $.ajax({
    headers: header,
    url: base + getBuildArea,
    data: {
      provinceId: provinceId ? provinceId : '',
      cityId: cityId ? cityId : ''
    }
  })
    .done(function (res) {
      console.log("初始化楼盘 success")
      console.log(res)

      let dom  = $('#propertyId'),
          html = '<option value="">请选择</option>',
          i    = 0,
          data = res,
          len  = data.length;

      for (; i < len; i++) {
        html += `<option value="${ data[i].propertyId }">${ data[i].propertyName }</option>`
      }

      dom.html(html)
      var buildSelect = dom.selectize()
      buildSelectize  = buildSelect[0].selectize
    })
    .fail(function (res) {
      console.log(res)

      layer.msg('获取楼盘失败', {
        icon: 5
      })
    })
    .always(function (res) {

      console.log("complete")
    })
}

function getBuildType (buildId) {
  $.ajax({
    headers: header,
    url: base + getBuildTypeList,
    data: {
      buildId: buildId
    }
  })
    .done(function (res) {
      console.log("初始化楼盘户型 success")
      console.log(res)

      let dom  = $('#propertyTypeId'),
          html = '<option value="">请选择</option>',
          i    = 0,
          data = res,
          len  = data.length;

      for (; i < len; i++) {
        html += `<option value="${ data[i].id }">${ data[i].name }</option>`
      }

      dom.html(html)
    })
    .fail(function (res) {
      console.log(res)

      layer.msg('获取楼盘户型失败', {
        icon: 5
      })

      console.log("error")
    })
    .always(function (res) {

      console.log("complete")
    })
}

// 点击列表的时候传递数据到全局变量
table.on('click-row.bs.table', (e, data, el) => {
  storeData = data;

  switch (storeData.channel) {
    case 'minsheng':
      bankUrl = minshengBank;
      break;
    default:
      bankUrl = bank
  }
})

// 搜索
$('#search-btn').on('click', (e) => {
  e.preventDefault();

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage: 1,
    }, $('#searchForm').serializeObject())
  })
})

// 状态搜索
$("input[name = 'payStatus']").on('change', (e) => {
  e.preventDefault();

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage: 1,
    }, $('#searchForm').serializeObject())
  })
})

// 导出
$('#export').on('click', (e) => {
  e.preventDefault()

  let data      = new Array(),
      tit,
      selectAll = $('input[name=btSelectAll]').prop('checked'),
      selection = table.bootstrapTable("getAllSelections"),
      option    = table.bootstrapTable("getOptions"),
      i         = 0,
      len       = selection.length;

  if (!selection.length) {
    layer.msg('没有选择数据', {
      icon: 5
    })

    return
  }

  // 盘点是否全选
  if (selectAll) {

    tit = `确认导出<span class="text-danger">【当前查询】</span>的数据吗`;
    data = [];

  } else {

    tit = `确认导出<span class="text-danger">【${len}】</span>条数据吗`;

    for (; i < len; i++) {
      data.push(selection[i].id)
    }
  }

  bootbox.confirm({
    title: '提示',
    message: `<div>
                <h3 style="margin:.75em 0">${ tit }</h3>
              </div>`,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: '导出'
      }
    },
    callback: (result) => {

      if (!result) {
        return
      }

      let loading_modal = layer.msg('Excel生成中...', {
        icon: 16,
        time: 0,
        shade: .5
      })

      $.ajax({
        headers: header,
        url: base + getPledgedExcel,
        type: 'POST',
        data: $.extend({}, $('#searchForm').serializeObject(), {
          pageSize: option.pageSize,
          pagination: option.pagination,
          serviceType: 'rcj',
          chk_value: data
        })
      })
        .done(function (res) {
          console.log(res)

          if (res.code === 0) {
            window.open(base + res.object);
          } else {
            layer.msg(res.message ? res.message : '获取excel失败', {
              icon: 5
            })
          }

          table.bootstrapTable('refresh')
        })
        .fail(function (res) {
          console.log(res)

          layer.msg('获取excel失败', {
            icon: 5
          })

        })
        .always(function (res) {

          layer.close(loading_modal)
        })
    }
  })

})

// 批量解冻
$('#batch-thaw').on('click', (e) => {
  e.preventDefault()

  let data      = new Array(),
      tit,
      selection = table.bootstrapTable("getAllSelections"),
      i         = 0,
      len       = selection.length;

  if (!selection.length) {
    layer.msg('没有选择数据', {
      icon: 5
    })

    return
  }

  tit = `确认解冻<span class="text-danger">【${len}】</span>条数据吗`;

  for (; i < len; i++) {
    data.push(selection[i].id)
  }

  bootbox.confirm({
    title: '提示',
    message: `<div>
                <h3 style="margin:.75em 0">${ tit }</h3>
              </div>`,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: '解冻'
      }
    },
    callback: (result) => {

      if (!result) {
        return
      }

      let loading_modal = layer.msg('解冻中...', {
        icon: 16,
        time: 0,
        shade: .5
      })

      data = data.join(',');

      $.ajax({
        headers: header,
        url: base + patchThaw,
        type: 'POST',
        data: {
          identOrderIds: data
        }
      })
        .done(function (res) {
          console.log(res)

          if (res.code === 0) {
            layer.msg(res.message ? res.message : '解冻成功', {
              icon: 6
            })
          } else {
            layer.msg(res.message ? res.message : '解冻失败', {
              icon: 5
            })
          }
          table.bootstrapTable('refresh')

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('解冻失败', {
            icon: 5
          })

        })
        .always(function (res) {

          layer.close(loading_modal)
          console.log("complete")

        })
    }
  })
})

// 批量退款
$('#batch-refund').on('click', (e) => {
  e.preventDefault()

  let data      = new Array(),
      tit,
      selection = table.bootstrapTable("getAllSelections"),
      i         = 0,
      len       = selection.length;

  if (!selection.length) {
    layer.msg('没有选择数据', {
      icon: 5
    })

    return
  }

  tit = `确认退款<span class="text-danger">【${len}】</span>条数据吗`;

  for (; i < len; i++) {
    data.push(selection[i].id)
  }

  bootbox.confirm({
    title: '提示',
    message: `<div>
                <h3 style="margin:.75em 0">${ tit }</h3>
              </div>`,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: '退款'
      }
    },
    callback: (result) => {

      if (!result) {
        return
      }

      let loading_modal = layer.msg('退款中...', {
        icon: 16,
        time: 0,
        shade: .5
      });

      data = data.join(',');

      $.ajax({
        headers: header,
        url: base + pathRefund,
        type: 'POST',
        data: {
          identOrderIds: data
        }
      })
        .done(function (res) {
          console.log(res)

          if (res.code === 0) {
            layer.msg(res.message ? res.message : '退款成功', {
              icon: 6
            })
          } else {
            layer.msg(res.message ? res.message : '退款失败', {
              icon: 5
            })
          }
          table.bootstrapTable('refresh')

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('退款失败', {
            icon: 5
          })

        })
        .always(function (res) {

          layer.close(loading_modal)
          console.log("complete")
        })
    }
  })

})

// 退款
$(document).on('click', '#table .refund', (e) => {
  e.preventDefault()

  console.log('退款')

  let id   = $(e.target).attr('data-id'),
      name = $(e.target).attr('data-name'),
      data = { identOrderId: id };

  bootbox.confirm({
    title: '退款',
    message: `<div>
                <h3 style="margin:.75em 0">确认退款该<span class="text-danger">【${ name }】</span>缴纳的金额吗？</h3>
              </div>`,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: '确认'
      }
    },
    callback: (result) => {

      if (!result) {
        return
      }

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0,
        shade: .5
      })

      $.ajax({
        headers: header,
        url: bankUrl + refund,
        type: 'POST',
        data: data
      })
        .done(function (res) {
          console.log(res)

          if (res.code === 0) {

            layer.msg('退款成功', {
              icon: 6
            })

          } else {
            layer.msg(res.message, {
              icon: 5
            })
          }
          table.bootstrapTable('refresh')

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('退款失败', {
            icon: 5
          })

        })
        .always(function (res) {

          console.log("complete")

          layer.close(loading_modal)
        })
    }
  })
})

// 已退
$(document).on('click', '#table .refunded', (e) => {
  e.preventDefault()

  console.log('已退')

  let id   = $(e.target).attr('data-id'),
      name = $(e.target).attr('data-name');
  bootbox.prompt({
    title: `警告,操作<span class="text-danger">【${ name }】</span>订单`,
    inputType: 'textarea',
    callback: function (result) {

      if (typeof result === 'string' && !result.length) {
        layer.msg('请输入备注')

        return false
      }

      if (!result) {
        return
      }

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0,
        shade: .5
      })

      $.ajax({
        headers: header,
        url: bankUrl + refunded,
        type: 'POST',
        data: {
          identOrderId: id,
          payStatus: 4,
          remark: result
        }
      })
        .done(function (d) {
          console.log(d)

          table.bootstrapTable('refresh')

          layer.close(loading_modal)

          layer.msg('操作成功', {
            icon: 6
          })

        })
        .fail(function (d) {
          console.log(d)

          layer.msg('操作失败', {
            icon: 5
          })

        })
        .always(function (res) {

          console.log("complete")

          layer.close(loading_modal)
        })
    }
  })
})

// 废弃
$(document).on('click', '#table .scrap', (e) => {
  e.preventDefault()

  console.log('废弃')

  let id   = $(e.target).attr('data-id'),
      name = $(e.target).attr('data-name')

  bootbox.prompt({
    title: '警告,操作【' + name + '】订单',
    inputType: 'textarea',
    callback: function (result) {

      console.log(result);
      if (typeof result === 'string' && !result.length) {
        layer.msg('请输入备注')

        return false
      }

      if (!result) {
        return
      }

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0,
        shade: .5
      })

      $.ajax({
        headers: header,
        url: bankUrl + refunded,
        type: 'POST',
        data: {
          identOrderId: id,
          payStatus: 2,
          remark: result
        }
      })
        .done(function (d) {
          console.log(d)

          table.bootstrapTable('refresh');

          layer.close(loading_modal)

          layer.msg('操作成功', {
            icon: 6
          })

        })
        .fail(function (d) {
          console.log(d)

          layer.msg('操作失败', {
            icon: 5
          })

        })
        .always(function (res) {

          console.log("complete");

          layer.close(loading_modal)
        })
    }
  })
})

// 解冻
$(document).on('click', '#table .thaw', (e) => {
  e.preventDefault()

  console.log('解冻')

  let id   = $(e.target).attr('data-id'),
      data = { identOrderId: id };

  bootbox.confirm({
    title: '提示',
    message: `<div>
                <h3 style="margin:.75em 0">是否解冻？</h3>
              </div>`,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: '解冻'
      }
    },
    callback: (result) => {

      if (!result) {
        return
      }

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0,
        shade: .5
      })

      $.ajax({
        headers: header,
        url: bankUrl + thaw,
        type: 'POST',
        data: data
      })
        .done(function (res) {
          console.log(res)

          if (res.code === 0) {

            layer.msg('解冻成功', {
              icon: 6
            })

            table.bootstrapTable('refresh')

          } else {
            layer.msg(res.message, {
              icon: 5
            })
          }

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('解冻失败', {
            icon: 5
          })

        })
        .always(function (res) {

          console.log("complete")

          layer.close(loading_modal)
        })
    }
  })
})

// 余额查询
$(document).on('click', '#table .balance', (e) => {
  e.preventDefault()

  console.log('余额查询')

  let loading = layer.msg('余额查询中...', {
    icon: 16,
    time: 0,
    shade: .5
  })

  let id   = $(e.target).attr('data-id'),
      data = { identOrderId: id }

  $.ajax({
    url: bankUrl + balance,
    headers: header,
    data: data
  })
    .done(function (res) {
      console.log(res)

      if (res.code === 0) {

        bootbox.alert(`<h3>总金额：${res.object.totalBlance} 元，可退金额：${ res.object.blance } 元</h3>`)

      } else {

        layer.msg(res.message, {
          icon: 5
        })

      }

    })
    .fail(function (res) {
      console.log(res)

      layer.msg('查询失败', {
        icon: 5
      })

    })
    .always(function (res) {
      layer.close(loading)
    })
})

// 验资
$(document).on('click', '#table .capital', (e) => {
  e.preventDefault()

  console.log('验资')

  let id   = $(e.target).attr('data-id'),
      data = { identOrderId: id, isPass: 'no' }

  let loading = layer.msg('验资中...', {
    icon: 16,
    time: 0,
    shade: .3
  })

  $.ajax({
    headers: header,
    url: bankUrl + capital,
    data: data
  })
    .done(function (res) {
      console.log(res)

      if (res.code === 0) {

        bootbox.alert(`<h3>${ res.message || '操作成功' }</h3>`)

        table.bootstrapTable('refresh')

      } else {
        bootbox.alert(`<h3>${ res.message }</h3>`)
      }

    })
    .fail(function (res) {
      console.log(res)

      layer.msg('验资失败', {
        icon: 5
      })

    })
    .always(function (res) {

      layer.close(loading)

    })
})

// 验资通过
$(document).on('click', '#table .capitalPass', (e) => {
  e.preventDefault()

  console.log('验资通过')

  let id   = $(e.target).attr('data-id'),
      data = {
        identOrderId: id,
        isPass: 'yes'
      }

  bootbox.confirm({
    title: '提示',
    message: `<div>
                <h3 style="margin:.75em 0">是否验资通过？</h3>
              </div>`,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: '确认'
      }
    },
    callback: (result) => {

      if (!result) {
        return
      }

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0,
        shade: .5
      })

      $.ajax({
        headers: header,
        url: bankUrl + capital,
        data: data
      })
        .done(function (res) {
          console.log(res)

          if (res.code === 0) {

            layer.msg('验资通过成功', {
              icon: 6
            })

            table.bootstrapTable('refresh')

          } else {
            layer.msg('验资通过失败', {
              icon: 5
            })
          }

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('验资失败', {
            icon: 5
          })

        })
        .always(function (res) {

          console.log("complete")

          layer.close(loading_modal)
        })
    }
  })
})

// 合同下载
$(document).on('click', '#table .contract', (e) => {
  e.preventDefault()

  console.log('合同下载')

  let id   = $(e.target).attr('data-id'),
      data = { identOrderId: id }

  $.ajax({
    headers: header,
    url: base + contract,
    type: 'POST',
    data: data
  })
    .done(function (res) {
      console.log(res)

      if (res.code == 0) {
        window.open(base + res.object)

      } else {
        layer.msg(res.message, {
          icon: 5
        })
      }

    })
    .fail(function (res) {
      console.log(res)

      layer.msg('获取失败', {
        icon: 5
      })

    })
    .always(function (res) {

      console.log("complete")

    })
})

// 告知书下载
$(document).on('click', '#table .notice', (e) => {
  e.preventDefault()

  console.log('解绑')

  let icNo = $(e.target).attr('data-icNo');

  window.open(base + notice + "?icNo=" + icNo)
})